<template>
    <div>

        <div class="title">
            <div class="desc">承担科研的项目
              <el-checkbox v-model="checked" @change="changeChecked">无(人才无承担科研的项目数据时，勾选该项;可完成人才新增)</el-checkbox>
            </div>
            <div class="box-wrap">
                <div class="line-item">
                    <el-button v-if="!checked" type="primary" @click="handleAdd" :disabled="flag == 3">添加</el-button>
                </div>
            </div>
        </div>

        <el-table :data="membersList" class="table">
            <el-table-column label="开始时间" width="150">
                <template #default="scope">
                    <el-date-picker v-if="activeIndex == scope.$index" v-model="scope.row.startTime" type="data"
                                    @change="changeStartTime(scope.row.startTime,scope.row.endTime,scope.$index)"
                        value-format="YYYY-MM-DD" placeholder="开始时间" clearable style="width: 100%" />
                    <span v-else>{{ scope.row.startTime }}</span>
                </template>
            </el-table-column>

            <el-table-column label="结束时间" width="150">
                <template #default="scope">
                    <el-date-picker v-if="activeIndex == scope.$index" v-model="scope.row.endTime" type="data"
                                    @change="changeEndTime(scope.row.startTime,scope.row.endTime,scope.$index)"
                        value-format="YYYY-MM-DD" placeholder="结束时间" clearable style="width: 100%" />
                    <span v-else>{{ scope.row.endTime }}</span>
                </template>
            </el-table-column>

            <el-table-column label="项目名称" width="280">
                <template #default="scope">
                  <el-input v-if="activeIndex == scope.$index"
                            v-model="scope.row.projectName"  @click="() => open(scope.$index)"
                            placeholder="请选择项目" maxlength="30" show-word-limit ></el-input>
                  <span v-else>{{ scope.row.projectName }}</span>
                </template>
            </el-table-column>

            <el-table-column label="级别" width="180">
<!--
                <template #default="scope">
                    <el-input v-if="activeIndex == scope.$index" v-model="scope.row.level" placeholder="请输入级别" maxlength="10" show-word-limit ></el-input>
                    <span v-else>{{ scope.row.level }}</span>
                </template>
-->
              <template #default="scope">
              <el-select v-if="activeIndex == scope.$index" v-model="scope.row.levelid" clearable placeholder="请输入级别"  @change="changeEducate($event, activeIndex)">
                <el-option :label="item.itemText" :value="item.itemValue" :key="item.itemValue"
                           v-for="item in leveltwoList"   />
              </el-select>
              <span v-else>{{ scope.row.level }}</span>
              </template>
            </el-table-column>

            <el-table-column label="担任角色" width="150">
<!--
                <template #default="scope">
                    <el-input v-if="activeIndex == scope.$index" v-model="scope.row.role" placeholder="担任角色" maxlength="10" show-word-limit ></el-input>
                    <span v-else>{{ scope.row.role }}</span>
                </template>
-->
              <template #default="scope">
                <el-select v-if="activeIndex == scope.$index" v-model="scope.row.role" clearable  @change="changeEducate($event, activeIndex)">
                  <el-option :label="item.itemText" :value="item.itemValue" :key="item.itemValue"
                             v-for="item in roleList"   />
                </el-select>
                <span v-else>{{ scope.row.role }}</span>
              </template>

            </el-table-column>
            <el-table-column align="right" width="250">
                <template #header>
                    <span>操作</span>
                </template>
                <template #default="scope">
                    <div v-if="activeIndex == scope.$index">

                        <el-button type="success" @click="handleSave">保存</el-button>
                      <el-popconfirm @confirm="handleDelete(scope.$index)" width="220" confirm-button-text="确定"
                                     cancel-button-text="取消" icon-color="#e6a23c" title="你确定要删除当前行?">
                        <template #reference>
                          <el-button type="danger" :disabled="flag == 3">删除</el-button>
                        </template>
                      </el-popconfirm>
                    </div>
                    <div v-else>
                        <el-button type="primary" @click="handleEdit(scope.$index)" :disabled="flag == 3">编辑</el-button>
                        <el-popconfirm @confirm="handleDelete(scope.$index)" width="220" confirm-button-text="确定"
                            cancel-button-text="取消" icon-color="#e6a23c" title="你确定要删除当前行?">
                            <template #reference>
                                <el-button type="danger" :disabled="flag == 3">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </div>
                </template>
            </el-table-column>
        </el-table>
    </div>
  <!-- 项目弹窗 -->
  <el-dialog v-model="Visible" width="1000px" top="17vh" :show-close="false" :close-on-click-modal="false">
    <template #title>
      <div class="my-header">
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="项目选择" name="first">
            <div class="search-box">
              <el-input v-model="xiangmuParams.projectName" placeholder="请输入" class="input-with-select"
                        style="width: 300px">
                <template #append>
                  <el-button type="primary" @click="open">搜索</el-button>
                </template>
              </el-input>
            </div>
            <el-table :data="options.xiangmuList" style="width: 100%" border @selection-change="handleSelectionChange1">
              <el-table-column type="selection" width="40" />
              <el-table-column prop="projectName" label="项目名称" width="200"  />
              <el-table-column prop="projectNumber" label="项目编号"  width="150" />
              <el-table-column prop="startTime" label="起止时间" width="150"  />
              <el-table-column prop="projectLeaderName" label="项目负责人" width="150"  />
              <el-table-column prop="projectTypeName" label="项目类型" width="150"  />
            </el-table>
            <div class="example-pagination-block">
              <el-pagination
                background
                layout="prev, pager, next ,total,sizes,jumper"
                :total="options.total"
                :page-size="xiangmuParams.size"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
        <div class="handle">
          <el-button color="#626aef" @click="Visible = false">关闭</el-button>
          <el-button type="primary" @click="toHandle1">关联</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>



<script  lang="ts">

import { reactive, ref, watch } from 'vue'
import { tips } from '@/views/science/components/tips/tips'
import { projectManagementListPage } from '@/views/science/technologyStrength/api/technologyStrength'

export default {


    components: {

    },
    emits: {
        dataChange: null,
        paramsChange: null,
    },
    props: {
      expertType: {
        type: Number,
        default: 1,
      },
        members: {
            type: Array,
            required: true,
        },
      roleList: {
        type: Array,
        required: true,
      },
      leveltwoList: {
        type: Array,
        required: true,
      },
      // falg  1:新增  2:编辑  3:详情
      flag: {
        type: String,
        default: '1',
      },
      isChecked: {
        type: Number,
        default: 1,
      },
    },
    setup(props, { emit }) {

        // const checked = ref(false)
        const checked = ref(!props.isChecked)

        let activeIndex = ref(-1);


        const membersList = ref(props.members) as any

        watch(props, (newValue, oldValue) => {
            membersList.value = newValue.members
        });
        watch(()=>props.isChecked, () => {
          console.log(checked.value,!props.isChecked,'research-ddasfwef');
          checked.value = !props.isChecked
        },{
          immediate:true
        });
      let  changeEducate=(id:any,currentRow:any)=>{

        let itemText = props.roleList.find((item:any) => item.itemValue == id).itemText;

        membersList.value[currentRow].roleId=id

        membersList.value[currentRow].role=itemText

      }
        const handleAdd = () => {

            let item = {
                startTime: '',
                endTime: '',
                projectName: '',
                level: '',
                role: ''
            };
            let flag = true
            membersList.value.every(item=>{
              console.log(item,'item');
              for(let key in item){
                if(item[key]===''){
                  flag =  false
                  return false
                }
              }
              return true
            })
            if(!flag){
              tips("请填写完整数据", "warning");

              return
            }
            membersList.value.push(item);

            activeIndex.value = membersList.value.length - 1;

        }

        const handleEdit = (index: number) => {

            activeIndex.value = index;
        };

        const handleSave = () => {



            let panduan = 0 ;
            membersList.value.forEach(item => {
              for (let i = 0; i < membersList.value.length; i++) {
                console.log(323232,item)
                if(item.startTime == null || item.startTime == ''){
                  panduan = 1;
                }
                if(item.endTime == null || item.endTime == ''){
                  panduan = 2;
                }
                if(item.projectName == null || item.projectName == ''){
                  panduan = 3;
                }
                if(item.role == null || item.role == ''){
                  panduan = 4;
                }

              }
            });
            if(panduan == 1){
              tips("数据中开始时间不能为空", "warning");
              // event.stopPropagation();
              return false;
            }else if(panduan == 2){
              tips("数据中结束时间不能为空", "warning");
              return false;
            }else if(panduan == 3){
              tips("数据中项目名称不能为空", "warning");
              return false;
            }else if(panduan == 4){
              tips("数据中担任角色不能为空", "warning");
              return false;
            }


          activeIndex.value = -1;
          emit('paramsChange', {list: membersList.value, checked: checked.value})

        };

        const handleDelete = (index: number) => {
            membersList.value.splice(index, 1);

            emit('paramsChange', {list: membersList.value, checked: checked.value})
        };
      const changeStartTime = (startTime,endTime,index) =>{
        let start = new Date(startTime).getTime()
        let end = new Date(endTime).getTime()
        if(start > end){
          tips("开始时间需要小于结束时间", "warning");
          membersList.value[index].startTime = ''
        }
        let duration = Math.trunc((end - start) / 2592000000)
        membersList.value[index].duration = duration > 0 ? duration : 0
        // console.log('changeStartTime',duration,membersList.value,index,);
      }
      const changeEndTime = (startTime,endTime,index) =>{
        let start = new Date(startTime).getTime()
        let end = new Date(endTime).getTime()
        if(start > end){
          tips("开始时间需要小于结束时间", "warning");
          membersList.value[index].endTime = ''
        }
        let duration = Math.trunc((end - start) / 2592000000)
        membersList.value[index].duration = duration > 0 ? duration : 0
      }
      const Visible = ref(false);
      const activeName = ref('first');
      //项目搜索参数
      const xiangmuParams = reactive({
        projectName: '',
        projectNumber: '',
        createOrgId: '',
        level: '',
        current: 1,
        size: 10,
        projectCategory: '1',
      });
      const options = reactive({
        xiangmuList: [], //项目列表
        projectList: [],
        contractList: [],
        total:0,
        isHightPayList:[
          {text:'否',value:'1',},
          {text:'是',value:'0',},
        ],
      });
      const tableIndex = ref<number>(0);
      const open = async (index?: number) => {
        console.log(props.expertType,'props.expertType');
        if(props.expertType != 1){
          return
        }
        if(index || index === 0) tableIndex.value = index;
        const res = await projectManagementListPage(xiangmuParams)
        const rs = res.data.data
        options.xiangmuList = rs.records
        options.total = rs.total
        Visible.value = true
      }
      const handleSelectionChange1 = (val) => {
        select1.value = val
      }
      const handleCurrentChange = (e) => {
        xiangmuParams.current = e
        open()
      }
      //改变页数限制
      const handleSizeChange = (e) => {
        xiangmuParams.size = e
        open()
      }
      const select1 = ref([]);
      const toHandle1 = () => {
        if (select1.value.length != 1) {
          tips('请选择一项关联', 'warning')
          return
        } else {
          const obj: any = select1.value[0];
          const row = membersList.value[tableIndex.value];
          row.projectName = obj.projectName;
          row.startTime = obj.startTime;
          row.endTime = obj.endTime;
          row.levelid = obj.level;
          // let itemValue = props.leveltwoList.find((item) => item.itemText == row.levelid).itemValue;
          // row.level = itemValue;
          let itemText = props.leveltwoList.find((item) => item.itemValue == row.levelid).itemText;
          row.level  = itemText;


          Visible.value = false
        }
      }
      const changeChecked = ()=>{
        emit('paramsChange', {list: membersList.value, checked: checked.value})
      }


        return {
            changeChecked,
            checked,
            membersList,
            activeIndex,
            handleAdd,
            handleEdit,
            handleSave,
            handleDelete,
          changeStartTime,
          changeEndTime,
          Visible,
          activeName,
          xiangmuParams,
          options,
          handleSelectionChange1,
          handleCurrentChange,
          handleSizeChange,
          toHandle1,
          open,
          changeEducate,
        }


    },
}
</script>












<style scoped lang="scss">
.box-wrap {
    display: flex;
    // .line-item:nth-child(1) {
    //     margin-right: 340px;
    //     font-size: 14px;
    //     align-items: center;
    //     display: flex;
    //     align-items: center;
    // }
}
.title {
    display: flex;
    justify-content: space-between;

    .desc {
        font-weight: bolder;
    }
}

.table {
    margin: 15px 0;
}
</style>
